package com.framework.web.sys.controller;

import com.framework.core.constant.Globals;
import com.framework.core.domain.SessionVo;
import com.framework.core.easyui.domain.Tree;
import com.framework.core.util.ContextHolderUtils;
import com.framework.core.util.MD5Util;
import com.framework.web.common.mappings.SysUrlMappings;
import com.framework.web.sys.domain.Resource;
import com.framework.web.sys.domain.User;
import com.framework.web.sys.service.LoginService;
import com.framework.web.sys.util.LogThreadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 用户登录管理
 *
 * @author fusf
 */
@Controller
public class LoginController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private LoginService loginService;


    /**
     * 页面刷新
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/")
    public ModelAndView initLoginGet(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = null;
        SessionVo sessionVo = ContextHolderUtils.getSessionVo();
        if (sessionVo != null) {//session没过期情况
            modelAndView = new ModelAndView(SysUrlMappings.V_INDEX);
        } else {
            modelAndView = new ModelAndView(SysUrlMappings.V_LOGIN);
        }
        return modelAndView;
    }


    /**
     * 用户登录登陆
     *
     * @param request
     * @param response
     * @param userName 用户名
     * @param userPwd  密码
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.LOGIN, method = RequestMethod.POST)
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response,
                              @RequestParam("userName") String userName, @RequestParam("userPwd") String userPwd) throws Exception {

        ModelAndView modelAndView = new ModelAndView(SysUrlMappings.V_INDEX);
        // 直接进入首页
        HttpSession session = ContextHolderUtils.getSession();
        session.removeAttribute(Globals.USER_SESSION);//清除session缓存
        User user = loginService.login(userName.trim(), MD5Util.encodeStr(userPwd.trim()));
        if (user != null) {
            if (Globals.USER_FORBIDDEN.equals(user.getStatus())) {//禁用状态
                modelAndView.addObject("userName", userName);
                modelAndView.addObject("message", "该用户已被注销，请联系管理员");
            } else {
                // 封装session对象属性
                SessionVo svo = new SessionVo();
                svo.setUserId(user.getId());//登录用户Id
                svo.setUserName(user.getUserName());//登陆用户名
                svo.setRealName(user.getRealName());//登录用户名称
                if (user.getOrganization() != null) { //组织机构
                    svo.setOrgId(user.getOrganization().getId());
                    svo.setOrgName(user.getOrganization().getOrgName());
                }
                session.setAttribute(Globals.USER_SESSION, svo);
                //获取用户权限
                Map<String, Object> map_authority = loginService.getAuthority(user.getId());
                session.setAttribute(Globals.USER_BUTTON_RES, map_authority);
                // 封装菜单列表
                Map<Integer, List<Resource>> map = loginService.getResourceMap(user.getId());
                session.setAttribute(Globals.USER_LEFT_MENU, map);

                //记录日志信息
                LogThreadUtil.saveLoginLog(svo, request, Globals.LOG_TYPE_LOGIN);
            }
        } else {
            modelAndView = new ModelAndView(SysUrlMappings.V_LOGIN);
            modelAndView.addObject("userName", userName);
            modelAndView.addObject("message", "用户名或密码不正确!");
        }
        return modelAndView;
    }


    /**
     * 页面刷新
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.LOGIN, method = RequestMethod.GET)
    public ModelAndView loginGet(HttpServletRequest request,
                                 HttpServletResponse response) throws Exception {
        ModelAndView modelAndView = null;
        SessionVo sessionV0_ = ContextHolderUtils.getSessionVo();
        if (sessionV0_ != null) {//session没过期情况
            modelAndView = new ModelAndView(SysUrlMappings.V_INDEX);
        } else {
            modelAndView = new ModelAndView(SysUrlMappings.V_LOGIN);
        }
        return modelAndView;
    }


    /**
     * 用户退出操作
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.LOGOUT)
    public ModelAndView logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        // 清空session
        session.invalidate();
        // 响应页面
        ModelAndView modelAndView = new ModelAndView(SysUrlMappings.V_LOGIN);
        return modelAndView;
    }


    /**
     * 获取资源菜单
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_MENU)
    @ResponseBody
    public List<Tree> getResourceList() throws Exception {
        return loginService.getTreeList();
    }


}
